package com.kws.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.core.domain.R;
import com.kws.common.core.enums.ModelOpType;
import com.kws.common.core.sys.Ksys;
import com.kws.common.core.utils.KConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.system.domain.SysMessageManage;
import com.kws.system.domain.SysMessageRemind;
import com.kws.system.domain.SysUserMessage;
import com.kws.system.domain.info.QueryMessageRemindInfo;
import com.kws.system.domain.vo.*;
import com.kws.system.mapper.SysMessageRemindMapper;
import com.kws.system.service.SysMessageManageService;
import com.kws.system.service.SysMessageRemindService;
import com.kws.system.service.SysUserMessageService;
import com.kws.system.util.SendMailUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <b>SysMessageRemindServiceImpl</b>
 *
 * @description: SysMessageRemindServiceImpl <br>
 * @date: 2024/11/5 17:41 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class SysMessageRemindServiceImpl extends ServiceImpl<SysMessageRemindMapper, SysMessageRemind> implements SysMessageRemindService {
    private static final Logger logger = LoggerFactory.getLogger(SysMessageRemindServiceImpl.class);

    @Autowired
    private SendMailUtil sendMailUtil;

    @Autowired
    private SysUserMessageService sysUserMessageService;

    private static String expression = "\\{([^\\{\\}]+)\\}";

    @Override
    public Page<QueryMessageRemindInfo> queryMessageRemindPage(Integer pageNum, Integer pageSize, String messageName) {
        Long userId = SecurityUtils.getUserId();
        Page<QueryMessageRemindInfo> page = new Page<>(pageNum, pageSize);
        Page<QueryMessageRemindInfo> pageInfo = baseMapper.queryMessageRemindPage(page,userId,messageName);
        if (CollectionUtil.isNotEmpty(pageInfo.getRecords())){
            pageInfo.getRecords().forEach(item -> {
                //根据消息ID查询消息关联用户
                List<String> userNameList = baseMapper.queryUserNameByMessageId(item.getMessageId());
                item.setUserNameList(userNameList);
            });
        }
        return pageInfo;
    }

    @Override
    public boolean createMessageRemind(SysMessageManage sysMessageManage) {
        SysMessageRemind sysMessageRemind = new SysMessageRemind();
        sysMessageRemind.setMessageId(sysMessageManage.getId());
        sysMessageRemind.setMessageType(sysMessageManage.getMessageType());
        sysMessageRemind.setMessageName(sysMessageManage.getMessageName());
        sysMessageRemind.setMessageContent(sysMessageManage.getMessageContent());
        sysMessageRemind.setMessageReceiver(sysMessageManage.getUserIdentity());
        sysMessageRemind.setSendTime(new Date());
        sysMessageRemind.setStatus("0");
        Ksys.setBasicModelData(sysMessageRemind,SecurityUtils.getStringUserId(), KConstants.DATA_ENABLE, ModelOpType.CREATE);
        int insert = baseMapper.insert(sysMessageRemind);
        if (1 == insert){
            return true;
        }
        return false;
    }

    @Override
    public QueryMessageRemindInfo queryMessageRemindById(Long id) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("status","1");
        updateWrapper.set("update_time",new Date());
        baseMapper.update(null,updateWrapper);
        QueryMessageRemindInfo info = baseMapper.queryMessageRemindById(id);
        if (null != info){
            //根据消息ID查询消息关联用户
            List<String> userNameList = baseMapper.queryUserNameByMessageId(info.getMessageId());
            if (CollectionUtil.isNotEmpty(userNameList)){
                info.setUserNameList(userNameList);
            }
        }
        return info;
    }

    @Override
    public boolean deleteMessageRemindById(Long id) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("enable","0");
        updateWrapper.set("update_user",SecurityUtils.getStringUserId());
        updateWrapper.set("update_time",new Date());
        int update = baseMapper.update(null, updateWrapper);
        if (1 == update){
            return true;
        }
        return false;
    }

    @Override
    public R CreateCheckGoodsOrderMessageRq(CreateCheckGoodsOrderMessageRq rq) throws NoSuchFieldException, IllegalAccessException {
        //查询核对商品订单消息模板信息
        SysMessageManage messageManage = baseMapper.queryMessageManageById(16l);
        if (null != messageManage){
            //解析商品信息
            String commodityName = null;
            String specificationAndModel = null;
            String commodityNumber = null;
            String commodityPrice = null;
            if (CollectionUtil.isNotEmpty(rq.getProductDetailsList())){
                commodityName = rq.getProductDetailsList().get(0).getCommodityName();
                specificationAndModel = rq.getProductDetailsList().get(0).getSpecificationAndModel();
                commodityNumber = rq.getProductDetailsList().get(0).getCommodityNumber();
                commodityPrice = rq.getProductDetailsList().get(0).getCommodityPrice();
                for (int i = 1; i < rq.getProductDetailsList().size(); i++) {
                    commodityName = commodityName+"、"+rq.getProductDetailsList().get(i).getCommodityName();
                    specificationAndModel = specificationAndModel + "、"+ rq.getProductDetailsList().get(i).getSpecificationAndModel();
                    commodityNumber = commodityNumber + "、" + rq.getProductDetailsList().get(i).getCommodityNumber();
                    commodityPrice = commodityPrice + "、"+ rq.getProductDetailsList().get(i).getCommodityPrice();
                }
                MessageParameterRq messageParameterRq = new MessageParameterRq();
                BeanUtil.copyProperties(rq,messageParameterRq);
                messageParameterRq.setCommodityName(commodityName);
                messageParameterRq.setSpecificationAndModel(specificationAndModel);
                messageParameterRq.setCommodityNumber(commodityNumber);
                messageParameterRq.setCommodityPrice(commodityPrice);
                String content = generateString(messageManage.getMessageContent(), messageParameterRq);
                //根据用户ID查询用户手机号
                SysUser user = baseMapper.queryUserByUserId(rq.getSendUserId());
                SysMessageRemind sysMessageRemind = new SysMessageRemind();
                sysMessageRemind.setMessageId(messageManage.getId());
                sysMessageRemind.setMessageType(messageManage.getMessageType());
                sysMessageRemind.setMessageName(messageManage.getMessageName());
                sysMessageRemind.setMessageContent(content);
                sysMessageRemind.setSendTime(new Date());
                sysMessageRemind.setMessageReceiver(user.getNickName());
                sysMessageRemind.setStatus("0");
                Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
                int insert = baseMapper.insert(sysMessageRemind);
                SysUserMessage sysUserMessage = new SysUserMessage();
                sysUserMessage.setUserId(rq.getSendUserId());
                sysUserMessage.setMessageId(sysMessageRemind.getId());
                boolean save = sysUserMessageService.save(sysUserMessage);
                //发送邮件
                sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
                if (1 == insert){
                    return R.ok();
                }
            }
        }
        return R.fail("创建失败");
    }

    @Override
    public R createCheckServeOrderMessage(CreateCheckServeOrderMessageRq rq) throws NoSuchFieldException, IllegalAccessException {
        //查询核对商品订单消息模板信息
        SysMessageManage messageManage = baseMapper.queryMessageManageById(17l);
        if (null != messageManage){
            String content = generateString(messageManage.getMessageContent(), rq);
            //根据用户ID查询用户手机号
            SysUser user = baseMapper.queryUserByUserId(rq.getSendUserId());
            SysMessageRemind sysMessageRemind = new SysMessageRemind();
            sysMessageRemind.setMessageId(messageManage.getId());
            sysMessageRemind.setMessageType(messageManage.getMessageType());
            sysMessageRemind.setMessageName(messageManage.getMessageName());
            sysMessageRemind.setMessageContent(content);
            sysMessageRemind.setSendTime(new Date());
            sysMessageRemind.setMessageReceiver(user.getNickName());
            sysMessageRemind.setStatus("0");
            Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
            int insert = baseMapper.insert(sysMessageRemind);
            SysUserMessage sysUserMessage = new SysUserMessage();
            sysUserMessage.setUserId(rq.getSendUserId());
            sysUserMessage.setMessageId(sysMessageRemind.getId());
            boolean save = sysUserMessageService.save(sysUserMessage);
            //发送邮件
            sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
            if (1 == insert){
                return R.ok();
            }
        }
        return R.fail("发送信息失败");
    }

    @Override
    public R createInviteEvaluationMessage(CreateInviteEvaluationMessageRq rq) throws NoSuchFieldException, IllegalAccessException {
        //查询核对商品订单消息模板信息
        SysMessageManage messageManage = baseMapper.queryMessageManageById(18l);
        if (null != messageManage){
            String content = generateString(messageManage.getMessageContent(), rq);//根据用户ID查询用户手机号
            SysUser user = baseMapper.queryUserByUserId(rq.getSendUserId());
            SysMessageRemind sysMessageRemind = new SysMessageRemind();
            sysMessageRemind.setMessageId(messageManage.getId());
            sysMessageRemind.setMessageType(messageManage.getMessageType());
            sysMessageRemind.setMessageName(messageManage.getMessageName());
            sysMessageRemind.setMessageContent(content);
            sysMessageRemind.setSendTime(new Date());
            sysMessageRemind.setMessageReceiver(user.getNickName());
            sysMessageRemind.setStatus("0");
            Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
            int insert = baseMapper.insert(sysMessageRemind);
            SysUserMessage sysUserMessage = new SysUserMessage();
            sysUserMessage.setUserId(rq.getSendUserId());
            sysUserMessage.setMessageId(sysMessageRemind.getId());
            boolean save = sysUserMessageService.save(sysUserMessage);
            //发送邮件
            sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
            if (1 == insert){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R createPaymentReminderMessage(CreatePaymentReminderMessageRq rq) throws NoSuchFieldException, IllegalAccessException {
        //查询核对商品订单消息模板信息
        SysMessageManage messageManage = baseMapper.queryMessageManageById(20l);
        if (null != messageManage){
            String content = generateString(messageManage.getMessageContent(), rq);//根据用户ID查询用户手机号
            SysUser user = baseMapper.queryUserByUserId(rq.getSendUserId());
            SysMessageRemind sysMessageRemind = new SysMessageRemind();
            sysMessageRemind.setMessageId(messageManage.getId());
            sysMessageRemind.setMessageType(messageManage.getMessageType());
            sysMessageRemind.setMessageName(messageManage.getMessageName());
            sysMessageRemind.setMessageContent(content);
            sysMessageRemind.setSendTime(new Date());
            sysMessageRemind.setMessageReceiver(user.getNickName());
            sysMessageRemind.setStatus("0");
            Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
            int insert = baseMapper.insert(sysMessageRemind);
            SysUserMessage sysUserMessage = new SysUserMessage();
            sysUserMessage.setUserId(rq.getSendUserId());
            sysUserMessage.setMessageId(sysMessageRemind.getId());
            boolean save = sysUserMessageService.save(sysUserMessage);
            //发送邮件
            sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
            if (1 == insert){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R createPostSalesServiceMessage(CreatePostSalesServiceMessageRq rq) throws NoSuchFieldException, IllegalAccessException {
        //查询核对商品订单消息模板信息
        SysMessageManage messageManage = baseMapper.queryMessageManageById(20l);
        if (null != messageManage){
            String content = generateString(messageManage.getMessageContent(), rq);//根据用户ID查询用户手机号
            SysUser user = baseMapper.queryUserByUserId(rq.getSendUserId());
            SysMessageRemind sysMessageRemind = new SysMessageRemind();
            sysMessageRemind.setMessageId(messageManage.getId());
            sysMessageRemind.setMessageType(messageManage.getMessageType());
            sysMessageRemind.setMessageName(messageManage.getMessageName());
            sysMessageRemind.setMessageContent(content);
            sysMessageRemind.setSendTime(new Date());
            sysMessageRemind.setMessageReceiver(user.getNickName());
            sysMessageRemind.setStatus("0");
            Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
            int insert = baseMapper.insert(sysMessageRemind);
            SysUserMessage sysUserMessage = new SysUserMessage();
            sysUserMessage.setUserId(rq.getSendUserId());
            sysUserMessage.setMessageId(sysMessageRemind.getId());
            boolean save = sysUserMessageService.save(sysUserMessage);
            //发送邮件
            sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
            if (1 == insert){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R createDeviceAlarmMessage(CreateDeviceAlarmMessageRq rq) throws NoSuchFieldException, IllegalAccessException {
        //查询核对商品订单消息模板信息
        SysMessageManage messageManage = baseMapper.queryMessageManageById(21l);
        if (null != messageManage){
            String content = generateString(messageManage.getMessageContent(), rq);//根据用户ID查询用户手机号
            SysUser user = baseMapper.queryUserByUserId(rq.getSendUserId());
            SysMessageRemind sysMessageRemind = new SysMessageRemind();
            sysMessageRemind.setMessageId(messageManage.getId());
            sysMessageRemind.setMessageType(messageManage.getMessageType());
            sysMessageRemind.setMessageName(messageManage.getMessageName());
            sysMessageRemind.setMessageContent(content);
            sysMessageRemind.setSendTime(new Date());
            sysMessageRemind.setMessageReceiver(user.getNickName());
            sysMessageRemind.setStatus("0");
            Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
            int insert = baseMapper.insert(sysMessageRemind);
            SysUserMessage sysUserMessage = new SysUserMessage();
            sysUserMessage.setUserId(rq.getSendUserId());
            sysUserMessage.setMessageId(sysMessageRemind.getId());
            boolean save = sysUserMessageService.save(sysUserMessage);
            //发送邮件
            sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
            if (1 == insert){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public <E> R createMessageNotification(E body) throws NoSuchFieldException, IllegalAccessException {
        Field field = body.getClass().getDeclaredField("messageTemplateType");
        field.setAccessible(true);
        String messageTemplateType = (String)field.get(body);
        SysMessageManage messageManage = baseMapper.queryMessageManageById(getMessageTemplateId(messageTemplateType));
        if (null != messageManage){
            String content = generateString(messageManage.getMessageContent(), body);//根据用户ID查询用户手机号
            Field sendUserField = body.getClass().getDeclaredField("sendUserId");
            sendUserField.setAccessible(true);
            Long sendUserId = (Long)sendUserField.get(body);
            SysUser user = baseMapper.queryUserByUserId(sendUserId);
            SysMessageRemind sysMessageRemind = new SysMessageRemind();
            sysMessageRemind.setMessageId(messageManage.getId());
            sysMessageRemind.setMessageType(messageManage.getMessageType());
            sysMessageRemind.setMessageName(messageManage.getMessageName());
            sysMessageRemind.setMessageContent(content);
            sysMessageRemind.setSendTime(new Date());
            sysMessageRemind.setMessageReceiver(user.getNickName());
            sysMessageRemind.setStatus("0");
            Ksys.setBasicModelData(sysMessageRemind,"sys",KConstants.DATA_ENABLE,ModelOpType.CREATE);
            int insert = baseMapper.insert(sysMessageRemind);
            SysUserMessage sysUserMessage = new SysUserMessage();
            sysUserMessage.setUserId(sendUserId);
            sysUserMessage.setMessageId(sysMessageRemind.getId());
            boolean save = sysUserMessageService.save(sysUserMessage);
            //发送邮件
            sendMailUtil.sendMail(messageManage.getMessageName(),content,user.getEmail());
            if (1 == insert){
                return R.ok();
            }
        }
        return R.fail();
    }

    public Long getMessageTemplateId(String messageTemplateType){
        Long messageTemplateId = 0l;
        switch(messageTemplateType) {
            case "checkGoodsOrder": //核对商品订单
                messageTemplateId = 16l;
                break;
            case "checkServeOrder": //核对服务订单
                messageTemplateId = 17l;
                break;
            case "inviteEvaluation": //邀请评价
                messageTemplateId = 18l;
                break;
            case "inviteOrder":  //邀请下单
                messageTemplateId = 19l;
                break;
            case "paymentReminder": //.付款提醒
                messageTemplateId = 20l;
                break;
            case "afterSalesService": //售后服务
                messageTemplateId = 21l;
                break;
            case "deviceAlarm": //设备告警
                messageTemplateId = 22l;
                break;
            case "policyDelivery": //策略下发
                messageTemplateId = 23l;
                break;
            case "serviceListingApproved": //服务上架审核通过
                messageTemplateId = 24l;
                break;
            case "productListingApproved": //商品上架审核通过
                messageTemplateId = 25l;
                break;
            case "settleThrough": //入驻通过
                messageTemplateId = 26l;
                break;
            case "contractSigning": //合同签订
                messageTemplateId = 27l;
                break;
            case "invoicingResult": //发票开具结果
                messageTemplateId = 28l;
                break;
            case "deliveryOfGoodsDistribution": //物流到货通知（配送）
                messageTemplateId = 29l;
                break;
            case "logisticsArrivalNoticeSelfPick": //物流到货通知（自提）
                messageTemplateId = 30l;
                break;
            case "noticeWorkOrderDistribution": //工单分发通知
                messageTemplateId = 31l;
                break;
            case "inspectionNotice": //巡检通知
                messageTemplateId = 32l;
                break;
            case "repairNotice": //报修通知
                messageTemplateId = 32l;
                break;
            case "rushRepairNotice":  //抢修通知
                messageTemplateId = 32l;
                break;
            default:
                messageTemplateId = null;
                break;
        }
        return messageTemplateId;
    }


    public <E> String generateString(String template, E obj) throws NoSuchFieldException, IllegalAccessException {
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(template);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()){
            String place = matcher.group(1);
            String value = getValueByPlace(place,obj);
            matcher.appendReplacement(sb,value);
        }
        matcher.appendTail(sb);
        String result = sb.toString();
        return result;
    }

    public <E> String getValueByPlace(String place, E obj) throws NoSuchFieldException, IllegalAccessException {
        String[] fieldNames = getFieldNames(obj.getClass());
        for (String fieldName : fieldNames) {
            if (place.equals(fieldName)){
                Field field = obj.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                return (String)field.get(obj);
            }
        }
        return "";
    }

    public static String[] getFieldNames(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

}
